import {useState} from 'react'
/**
 * 自定义hook
 */

// V1：获取本地存储数据
// export function useStorage(key){
//     let data = localStorage.getItem(key);// string,json,null

//     try{
//         data = JSON.parse(data)
//     }catch(err){
        
//     }

//     return data
// }

// V2：实现本地存储的读写
export function useStorage(key){
    let data = localStorage.getItem(key);// string,json,null
    try{
        data = JSON.parse(data)
    }catch(err){
        
    }

    // 解决组件刷新问题
    const [state,setState] = useState(data)

    const change = function(newValue){
        setState(newValue);

        if(typeof newValue === 'object'){
            newValue = JSON.stringify(newValue)
        }

        localStorage.setItem(key,newValue)
    }


    return [state,change]
}

export function useUser(){
    return useStorage('user')
}